package com.xhwl.centiotdata.service.integrateconfig;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xhwl.centiotdata.pojo.dto.alarmhost.AlarmHostIntegrationConfigDTO;
import com.xhwl.common.enums.CategoryEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author： lianghz
 * @Description：
 * @Date 2021/12/17/ 11:45
 */
@Component
@Slf4j
public class AlarmHostIntegrationConfig extends IntegrationConfig<Object, Map<Integer, List<AlarmHostIntegrationConfigDTO>>> {

    private Map<Integer, List<AlarmHostIntegrationConfigDTO>> alarmHostIntegrationConfigMap = new HashMap<>();


    @Override
    public Map<Integer, List<AlarmHostIntegrationConfigDTO>> getIntegrationConfig(Object o) {
        return alarmHostIntegrationConfigMap;
    }

    /**
     * 配置变更时，重新赋值map
     *
     * @param event
     */
    @EventListener
    public void listenIntegrationConfig(IntegrationConfigEvent event) {
        this.handleAlarmHostIntegrationConfig();
    }


    private void handleAlarmHostIntegrationConfig() {
        alarmHostIntegrationConfigMap = IntegrationConfig.integrationConfigList.stream().filter(deviceProjSupplierCategory ->
                CategoryEnum.ALARM_HOST_SYSTEM.getId().equals(deviceProjSupplierCategory.getProdCategoryId())
                && deviceProjSupplierCategory.getProperties() != null).map(deviceProjSupplierCategory -> {
            JSONObject properties = deviceProjSupplierCategory.getProperties();
            AlarmHostIntegrationConfigDTO propertiesDTO = JSON.toJavaObject(properties, AlarmHostIntegrationConfigDTO.class);
            AlarmHostIntegrationConfigDTO configDTO = new AlarmHostIntegrationConfigDTO();
            BeanUtils.copyProperties(propertiesDTO, configDTO);
            configDTO.setProjectId(deviceProjSupplierCategory.getProjectId());
            configDTO.setProductId(deviceProjSupplierCategory.getProductId());
            return configDTO;
        }).collect(Collectors.groupingBy(AlarmHostIntegrationConfigDTO::getProjectId));
    }
}
